using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

/// <summary>
/// 控制场景切换时的黑色淡入淡出动画，用于增强用户体验（如切换时防止画面突变）
/// </summary>
public class SceneTransitionManager : MonoBehaviour
{
    [Header("淡入淡出参数")]
    [SerializeField] private Image fadeImage;     // 覆盖整个屏幕的黑色图片
    [SerializeField] private float fadeSpeed = 1f; // 控制淡入淡出的速度（单位 alpha/秒）

    private void Start()
    {
        // 场景刚加载完时画面为全黑
        SetAlpha(1f);

        // 执行淡入效果（从黑到透明）
        StartCoroutine(FadeSceneIn());
    }

    /// <summary>
    /// 外部调用：加载目标场景（自动淡出）
    /// </summary>
    public void LoadScene(string sceneName)
    {
        StartCoroutine(FadeSceneOut(sceneName));
    }

    /// <summary>
    /// 执行场景淡出 + 加载新场景
    /// </summary>
    private IEnumerator FadeSceneOut(string sceneName)
    {
        yield return StartCoroutine(Fade(1f));               // 淡出至黑色
        SceneManager.LoadScene(sceneName);                   // 加载场景
    }

    /// <summary>
    /// 场景加载后执行的淡入操作（从黑到透明）
    /// </summary>
    private IEnumerator FadeSceneIn()
    {
        yield return StartCoroutine(Fade(0f));               // 淡入显示内容
    }

    /// <summary>
    /// 淡入淡出通用方法
    /// </summary>
    private IEnumerator Fade(float targetAlpha)
    {
        Color color = fadeImage.color;
        float startAlpha = color.a;
        float fadeDuration = Mathf.Abs(targetAlpha - startAlpha) / fadeSpeed;
        float elapsedTime = 0f;

        while (elapsedTime < fadeDuration)
        {
            elapsedTime += Time.deltaTime;
            float newAlpha = Mathf.Lerp(startAlpha, targetAlpha, elapsedTime / fadeDuration);
            SetAlpha(newAlpha);
            yield return null;
        }

        SetAlpha(targetAlpha); // 确保结束时为目标透明度
    }

    /// <summary>
    /// 设置遮罩图的透明度
    /// </summary>
    private void SetAlpha(float alpha)
    {
        if (fadeImage != null)
        {
            Color color = fadeImage.color;
            color.a = alpha;
            fadeImage.color = color;
        }
    }
}
